﻿using Fleck;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YB;
using YB_PrintPlug;
using static YB.WebSocket;
using System.Threading.Channels;
using NAudio.Wave;
using System.Threading;
using System.Net.WebSockets;
using WebSocketSharp;
using Newtonsoft.Json.Schema;
using System.Linq;
using System.Collections.Specialized;
using System.Net.Sockets;
using System.Timers;
using NPOI.OpenXmlFormats.Dml.Chart;
using NPOI.SS.Formula.Functions;
using NPOI.POIFS.Crypt.Dsig;
using System.IO.Compression;
namespace YB_Server_Windows
{
    public partial class main : Form
    {
        private static string MachLogisticsCode(string s)
        {
            //Log.Write("开始转换单号" + s);
            int firstDashIndex = s.IndexOf("-");
            int lastDashIndex = s.LastIndexOf("-");
            // 如果没有找到第一个或最后一个'-'，或者它们是同一个位置，直接返回原字符串
            if (firstDashIndex == -1 || lastDashIndex == -1 || firstDashIndex == lastDashIndex)
            {
                return s;
            }
            // 其他的处理
            string processedString = s.Substring(0, firstDashIndex) + s.Substring(lastDashIndex + 1);
            return processedString;
        }
        private OrderedDictionary uniqueDictionary = new OrderedDictionary();
        private SseClient mainsseclient = null;

        private string socketToken = "";
        private Dictionary<string, YbMakeExcel> excelMap = new Dictionary<string, YbMakeExcel>();
        private string _Parameterstr = "-r 15 -f gdigrab -i desktop -f dshow $audio -b:v 1200k -bufsize 1m -c:v libx264 -preset ultrafast -y $filename";
        private Dictionary<string, Goods> MaterialSkuMap = new Dictionary<string, Goods>();
        private Dictionary<string, byte[]> AudioMap = new Dictionary<string, byte[]>();
        private int OrderCount = 0;
        private int postOrderCount = 0;
        private static Channel<OrderPostData> orderChannet;
        private Dictionary<string, string> errAudioMap = new Dictionary<string, string>();
        private bool loadOver = false;
        private WebSocketSharp.WebSocket _mainSocket = null;
        private bool socketOnline = false;
        private Image mainAvatar = null;
        public class mainStockData
        {
            public string Datastr { get; set; }
            public string Data { get; set; }
            public string Sn { get; set; }
            public string Uid { get; set; }
            public string Sid { get; set; }
            public string SendTime { get; set; }
            public string Command { get; set; }
            public string Type { get; set; }
            public int Count { get; set; }
            public int Index { get; set; }
            public string TaskSN { get; set; }
            public string SendSn { get; set; }
            public int MessageType { get; set; } //消息类型,文本，二进制
            public bool URLencoder { get; set; }
        }
        private class OrderPostData
        {
            public string Index { get; set; }
            public string BillNo { get; set; }
            public string Pkey { get; set; }
            public Dictionary<string, Object> Data { get; set; }
            public SaleOrderInfo SaleOrder { get; set; }
        }
        public class VideoConfig
        {
            public string Key { get; set; }
            public string Name { get; set; }
            public string Value { get; set; }
        }
        public class SaleOrderInfo
        {
            public string Id;
            public string BillNo;
            public string Weight;
            public string MaterialName;
            public bool Usedgoodsweight;
            public string State;
            public string Pkey;
        }
        public class Goods
        {
            public Goods(string id, string goodsname, string goodssn, string goodsimg)
            {
                this.Id = id;
                this.GoodsName = goodsname;
                this.GoodsSn = goodssn;
                this.GoodsImg = goodsimg;
            }
            public string Id { get; set; }
            public string GoodsName { get; set; }
            public string GoodsSn { get; set; }
            public string GoodsImg { get; set; }
            public string Tid { get; set; }
        }
        public class ComboItem
        {
            public string Name { get; set; }
            public string Id { get; set; }
            public string GetValue()
            {
                return Id;
            }
        }
        public class PrintTask_Data
        {
            public string Index { get; set; }
            public string State { get; set; }
            public string TaskId { get; set; }
            public string PlugName { get; set; }
            public string CreateTime { get; set; }
            public PrintTask_Data(string index, string taskid)
            {
                Index = index;
                TaskId = taskid;
            }
        }
        public class PrintListView
        {
            public string Index;
            public string State;
            public string TaskId;
            public string PlugName;
            public string CreateTime;
            public int OrderCount;
            public Image Icon;
            public PrintListView(string index, string state, string taskid, string plugname)
            {
                Index = index;
                State = state;
                TaskId = taskid;
                PlugName = plugname;
                CreateTime = DateTime.Now.ToString();
            }
        }
        ComboItem[] weightType = new ComboItem[] { new ComboItem() { Name = "电子秤数据", Id = "1" }, new ComboItem() { Name = "手动输入", Id = "2" }, new ComboItem() { Name = "按预估重量", Id = "3" } };
        ComboItem[] packagingType = new ComboItem[] { new ComboItem() { Name = "记住上次", Id = "1" }, new ComboItem() { Name = "不使用包材", Id = "2" }, new ComboItem() { Name = "每次必选", Id = "3" } };

        public static System.Windows.Forms.TabControl MainTabControl { get; set; }
        public static System.Windows.Forms.TabControl _PrintTab { get; set; }
        public static System.Windows.Forms.TabControl _PrintTaskList { get; set; }
        public static System.Windows.Forms.Form thisForm { get; set; }
        private static Dictionary<string, YBListView> _listviewMap = new Dictionary<string, YBListView>();
        private static FlowLayoutPanel _printcommandbuttongroup { get; set; }
        JObject WebConfig = new JObject();
        JObject FFmpegConfig = new JObject();
        JObject WebSocketConfig = new JObject();
        public void SetControlEnable(Control control, bool enabled)
        {
            control.Enabled = enabled;
            foreach (Control childControl in control.Controls)
            {
                SetControlEnable(childControl, enabled);
            }
        }

        public main()
        {

            thisForm = this;
            orderChannet = Channel.CreateBounded<OrderPostData>(100);
            Task.Run(async () =>
            {
                while (await orderChannet.Reader.WaitToReadAsync())
                {
                    if (orderChannet.Reader.TryRead(out OrderPostData postData))
                    {
                        Task<YB.returnmsg> mlisttask = YbWeb.Post(User.GetHostUrl() + "/wmsapi/getinfo/", "packagesend", postData.Data);
                        YB.returnmsg response = await mlisttask;
                        postData.SaleOrder.State = "正在提交服务器...";
                        ybListView1.Update(postData.SaleOrder);
                        thisForm.Invoke((Action)(() =>
                        {
                            //这里要更新内容
                            if (response.Errcode != 0)
                            {
                                DbScanInputBox.Focus();
                                byte[] errAudioMap = AudioMap["ordernotfind"];
                                if (AudioMap.ContainsKey(response.Errmsg))
                                {
                                    errAudioMap = AudioMap[response.Errmsg];
                                }
                                else
                                {
                                    foreach (string key in AudioMap.Keys)
                                    {
                                        if (response.Errmsg.Contains(key))
                                        {
                                            errAudioMap = AudioMap[key];
                                            break;
                                        }
                                    }
                                }
                                postData.SaleOrder.State = "错误信息[" + response.Errmsg + "]";
                                ybListView1.Update(postData.SaleOrder);
                                PlayAudio(errAudioMap);
                            }
                            else
                            {
                                PlayAudio(AudioMap["success"]);
                                DbScanInputBox.Focus();
                                postData.SaleOrder.State = "已完成";
                                ybListView1.Delete(postData.SaleOrder);
                                postOrderCount++;
                                showCount();
                            }
                        }));

                    }
                    else
                    {
                        // 通道关闭，没有更多消息
                        Console.WriteLine("Channel has been closed and no more messages to read.");
                        break;
                    }
                }
            });

            //初始化错误数据
            //errAudioMap["使用期限已过期，请及时续费"] = "启动Http服务端错误";
            errAudioMap["重量必须大于0"] = "重量必须大于0";
            errAudioMap["该订单没有验货，不能打包发货"] = "该订单没有验货不能打包发货";
            errAudioMap["称重过程中发生错误"] = "称重过程中发生错误";
            foreach (string key in errAudioMap.Keys)
            {
                AudioMap[key] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject(errAudioMap[key]));
            }
            AudioMap["changeMaterial"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("changeMaterial"));
            AudioMap["ordernotfind"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("ordernotfind"));
            AudioMap["success"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("success"));
            AudioMap["materialclear"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("materialclear"));
            AudioMap["bgendownload"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("bgendownload"));
            AudioMap["billnoempty"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("billnoempty"));
            AudioMap["weight0"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("weight0"));
            AudioMap["needmaterial"] = Convert.FromBase64String((string)Properties.Resources.ResourceManager.GetObject("needmaterial"));
            InitializeComponent();
            selectWeightType.DataSource = weightType;
            selectWeightType.DisplayMember = "Name";
            selectWeightType.ValueMember = "Id";

            try
            {
                JObject DZC = YB.Config.ReadConfig("DZC");
                Console.WriteLine(DZC.ToString());
                YB.Log.Write("读取默认选择");
                if (DZC != null)
                {
                    string selectWeightTypevalue = "1";
                    YB.Config.ReadJObject(DZC, "WeightType", ref selectWeightTypevalue);
                    int selectindex = int.Parse(selectWeightTypevalue) - 1;
                    selectWeightType.SelectedIndex = selectindex;
                }
            }
            catch (Exception ex)
            {

            }
            selectPackagingType.DataSource = packagingType;
            selectPackagingType.DisplayMember = "Name";
            selectPackagingType.ValueMember = "Id";

            MainTabControl = tabControl1;
            SetControlEnable(MainTabControl.TabPages[5], false);
            _PrintTab = PrintTab;
            _PrintTaskList = PrintTaskTab;

            _printcommandbuttongroup = printcommandbuttongroup;

            ybListView1.SetPkey("Pkey");
            List<YBListView.Columns> columns = new List<YBListView.Columns>();
            columns.Add(new YBListView.Columns("序号", "Id", 70));
            columns.Add(new YBListView.Columns("物流单号", "BillNo", 150));
            columns.Add(new YBListView.Columns("重量", "Weight", 100));
            columns.Add(new YBListView.Columns("包装材料", "MaterialName", 150));
            columns.Add(new YBListView.Columns("使用预估重量", "Usedgoodsweight", 90));
            columns.Add(new YBListView.Columns("状态", "State", 300));
            ybListView1.SetColumns(columns);
            ybListView1.SetDrawRow(GetRowColor);
        }
        private Color GetRowColor(Dictionary<string, object> rowData)
        {
            Color outData = Color.Transparent;
            if (rowData.ContainsKey("State"))
            {
                string nowState = rowData["State"].ToString();
                switch (nowState)
                {
                    case "已完成":
                        return Color.FromArgb(255, 200, 255, 200);
                    case "准备中...":
                        return Color.Transparent;
                    case "正在提交服务器...":
                        return Color.FromArgb(255, 200, 200, 240);
                    default:
                        return Color.FromArgb(255, 255, 200, 200);
                }
            }
            return outData;
        }

        private void AddLog(string message)
        {
            if (loglist.InvokeRequired)
            {
                loglist.Invoke(new Action<string>(AddLog), message);
            }
            else
            {
                loglist.Items.Insert(0, DateTime.Now.ToString() + ":" + message);
                if (loglist.Items.Count > 200)
                {
                    for (int i = loglist.Items.Count - 1; i >= 200; i--)
                    {
                        loglist.Items.RemoveAt(i);
                    }
                }
            }
        }
        private async Task checkUpdate(bool showmsg = false)
        {
            //_printcommandbuttongroup.Invoke((Action)(() =>
            //{
            //    ProcessStartInfo processStartInfo = new ProcessStartInfo
            //    {
            //        FileName = "update.exe",
            //        RedirectStandardInput = true,
            //        RedirectStandardError = true,
            //        UseShellExecute = false,
            //        Arguments = "-checkupdate updateEventPipe",
            //    };
            //    Process process = new Process
            //    {
            //        StartInfo = processStartInfo
            //    };
            //    try
            //    {
            //        var info = process.Start();
            //        Console.WriteLine(info);
            //        process.WaitForExit();
            //        int exitCode = process.ExitCode;
            //        if (exitCode == 1)
            //        {
            //            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "update.exe");
            //        }
            //        else
            //        {
            //            if (showmsg)
            //            {
            //                MessageBox.Show("当前已是最新版本咯!", "自动更新", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            //            }
            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            //    }
            //}));
            //先检查用最新的update来检测更新
            string url = "https://www.jxwms.net/static/jxos/update.json"; // 指定URL，替换为实际的URL
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    Assembly assembly = Assembly.GetEntryAssembly();
                    // 获取当前程序集的版本号
                    Version version = assembly.GetName().Version;
                    string versionNumber = version.ToString();

                    // 发送GET请求并获取响应内容
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();


                    // 将响应内容转换为JSON对象
                    JObject jsonData = JObject.Parse(responseBody);


                    if (jsonData != null)
                    {
                        string newvar = jsonData["var"].ToString();
                        if (newvar != null && newvar != "")
                        {
                            Version v1 = new Version(versionNumber);
                            Version v2 = new Version(newvar);
                            int result = v1.CompareTo(v2);
                            if (result < 0)
                            {
                                Process.Start(AppDomain.CurrentDomain.BaseDirectory + "update.exe");
                                Environment.Exit(0);
                            }
                            else
                            {
                                if (showmsg)
                                {
                                    MessageBox.Show("当前已是最新版本咯!", "自动更新", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                YB.Log.Write("检查更新失败" + ex.ToString());
            }
        }
        public static void RecoverPrintFun(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            Printlist.Continue(button.Tag.ToString());
        }
        public static void ClearPrintFun(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            Printlist.ClearPrint(button.Tag.ToString());
        }

        public static void ShowPrintCount(string printname, int count)
        {
            if (_PrintTab.TabPages.ContainsKey(printname))
            {
                if (count > 0)
                {
                    _PrintTab.TabPages[printname].Text = _PrintTab.TabPages[printname].Name + "(" + count.ToString() + ")";
                }
                else
                {
                    _PrintTab.TabPages[printname].Text = _PrintTab.TabPages[printname].Name;
                }

            }
        }
        public static void RefreshPrintButton()
        {
            _printcommandbuttongroup.Invoke((Action)(() =>
            {
                _printcommandbuttongroup.Controls.Clear();
                bool hasbutton = Printlist.CheckWaitNext(_PrintTaskList.SelectedTab.Name);
                if (hasbutton)
                {
                    Button RecoverPrint = new Button();
                    RecoverPrint.Text = "继续打印";
                    RecoverPrint.Tag = _PrintTaskList.SelectedTab.Name;
                    RecoverPrint.Click += RecoverPrintFun;
                    Button ClearPrint = new Button();
                    ClearPrint.Text = "取消打印";
                    ClearPrint.Tag = _PrintTaskList.SelectedTab.Name;
                    ClearPrint.Click += ClearPrintFun;
                    _printcommandbuttongroup.Controls.Add(RecoverPrint);
                    _printcommandbuttongroup.Controls.Add(ClearPrint);
                }
            }));

        }
        public static YB.errmsg AddPrintLog(string printname, string text)
        {

            if (_PrintTab.TabPages.ContainsKey(printname))
            {
                ListBox listBox = (ListBox)_PrintTab.TabPages[printname].Controls[0];
                listBox.Items.Insert(0, text);
                return null;
            }
            else
            {
                return new YB.errmsg(7011, "没有找到相应的打印机");
            }
        }
        public static List<YB_PrintPlug.PrintPlug> GetPrintPlugs()
        {
            List<PrintPlug> outData = new List<PrintPlug>();
            for (int i = 0; i < MainTabControl.TabPages[3].Controls.Count; i++)
            {
                outData.Add((PrintPlug)MainTabControl.TabPages[3].Controls[i]);
            }
            return outData;
        }
        public static string GetPrintPlugName(string kind)
        {
            for (int i = 0; i < MainTabControl.TabPages[3].Controls.Count; i++)
            {
                if (MainTabControl.TabPages[3].Controls[i].Name == kind)
                {
                    PrintPlug thisplug = (PrintPlug)MainTabControl.TabPages[3].Controls[i];
                    return thisplug.Label;
                }
            }
            return "";
        }
        public static YB_PrintPlug.PrintPlug GetPrintPlug(string kind)
        {
            for (int i = 0; i < MainTabControl.TabPages[3].Controls.Count; i++)
            {
                if (MainTabControl.TabPages[3].Controls[i].Name == kind)
                {
                    return (PrintPlug)MainTabControl.TabPages[3].Controls[i];
                }
            }
            return null;
        }
        private void LoadFFmpegConfig()
        {
            Console.WriteLine("载入录像设置");
            FFmpegConfig = YB.FFmpeg.GetConfig();
            string parameter = "";
            YB.Config.ReadJObject(FFmpegConfig, "Parameter", ref parameter);
            Parameter.Text = parameter;
            string ffmpegpath = "";
            YB.Config.ReadJObject(FFmpegConfig, "FFmpegPath", ref ffmpegpath);
            FFmpegPath.Text = ffmpegpath;
            string savefilepath = "";
            YB.Config.ReadJObject(FFmpegConfig, "SaveFilePath", ref savefilepath);
            SaveFilePath.Text = savefilepath;
            var audiolist = YB.FFmpeg.GetDriverName("(audio)");
            foreach (string item in audiolist)
            {
                AutioDriver.Items.Add(item);
            }
            string autiodriver = "";
            YB.Config.ReadJObject(FFmpegConfig, "AutioDriver", ref autiodriver);
            AutioDriver.Text = autiodriver;
            long diskminsize = 0;
            YB.Config.ReadJObject<long>(FFmpegConfig, "DiskMinSize", ref diskminsize);
            DiskMinSize.Value = diskminsize;
            bool autodelfile = false;
            YB.Config.ReadJObject<bool>(FFmpegConfig, "AutoDelFile", ref autodelfile);
            AutoDelFile.Checked = autodelfile;
            bool autouploadfile = false;
            YB.Config.ReadJObject<bool>(FFmpegConfig, "AutoUpdateFile", ref autouploadfile);
            AutoUpdateFile.Checked = autouploadfile;
            string uploadserverurl = "https://s4.z100.vip:16948/upload";
            YB.Config.ReadJObject<string>(FFmpegConfig, "UploadServerUrl", ref uploadserverurl);
            Console.WriteLine("录像配置" + JsonConvert.SerializeObject(FFmpegConfig));
            UploadServerUrl.Invoke((Action)(() =>
            {
                UploadServerUrl.Text = uploadserverurl;
            }));
            int maxrecodtime = 60;
            YB.Config.ReadJObject<int>(FFmpegConfig, "MaxRecodTime", ref maxrecodtime);
            UploadServerUrl.Invoke((Action)(() =>
            {
                MaxRecodTime.Value = maxrecodtime;
            }));

        }
        private void main_Load(object sender, EventArgs e)
        {

            //开始检查版本
            checkUpdate();
            YB.Log.Write("进入main_load");
            //绑定日志写入完成更新当前的日志查看
            tabControl1.SelectedIndex = 0;
            YB.Log.SetOnFinish(AddLog);
            AddLog("服务已启动");
            //初始化FFmpeg
            YB.Log.Write("开始初始化录像功能");
            YB.FFmpeg.LoadConfig();
            LoadFFmpegConfig();
            if (AutoUpdateFile.Checked)
            {
                YB.FFmpeg.BgenUpLoadFile();//开始自动上传文件
            }

            //初始化打印机
            YB.PrintTask.Init();
            List<YB.PrintTask.PrintListItem> printList = YB.PrintTask.GetPrintList();
            foreach (YB.PrintTask.PrintListItem item in printList)
            {
                YBListView printlistbox = new YBListView();
                List<YBListView.Columns> columns = new List<YBListView.Columns>();
                columns.Add(new YBListView.Columns("序号", "Index", 60));
                columns.Add(new YBListView.Columns("状态", "State", 100));
                columns.Add(new YBListView.Columns("图标", "Icon", 80));
                columns.Add(new YBListView.Columns("打印组件", "PlugName", 90));
                columns.Add(new YBListView.Columns("订单数", "OrderCount", 60));
                columns.Add(new YBListView.Columns("任务ID", "TaskId", 260));
                columns.Add(new YBListView.Columns("创建时间", "CreateTime", 60));
                ListBox listBox = new ListBox();
                printlistbox.SetColumns(columns);
                printlistbox.SetPkey("TaskId");
                TabPage tab = new TabPage();
                tab.Text = item.Name;
                tab.Name = item.Name;
                tab.Controls.Add(listBox);
                listBox.Dock = DockStyle.Fill;
                PrintTab.TabPages.Add(tab);
                //再添加一个打印控制按钮组
                //DataGridView printlistbox = new DataGridView();
                //printlistbox.Name = item.Name;


                //DataGridViewTextBoxColumn index = new DataGridViewTextBoxColumn();
                //index.HeaderText = "序号";
                //index.Width = 60;
                //index.DataPropertyName = "Index";
                //index.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(index);
                //DataGridViewTextBoxColumn state = new DataGridViewTextBoxColumn();
                //state.HeaderText = "状态";
                //state.Width = 80;
                //state.DataPropertyName = "State";
                //state.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(state);
                //DataGridViewImageColumn icon = new DataGridViewImageColumn();
                //icon.HeaderText = "图标";
                //icon.Width = 40;
                //icon.DataPropertyName = "Icon";
                //icon.ImageLayout = DataGridViewImageCellLayout.Zoom;
                //icon.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(icon);
                //DataGridViewTextBoxColumn plug = new DataGridViewTextBoxColumn();
                //plug.HeaderText = "打印组件";
                //plug.Width = 80;
                //plug.DataPropertyName = "PlugName";
                //plug.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(plug);
                //DataGridViewTextBoxColumn ordercount = new DataGridViewTextBoxColumn();
                //ordercount.HeaderText = "订单数";
                //ordercount.Width = 60;
                //ordercount.DataPropertyName = "OrderCount";
                //ordercount.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(ordercount);
                //DataGridViewTextBoxColumn taskid = new DataGridViewTextBoxColumn();
                //taskid.HeaderText = "任务ID";
                //taskid.Width = 300;
                //taskid.DataPropertyName = "TaskId";
                //taskid.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(taskid);
                //DataGridViewTextBoxColumn createtime = new DataGridViewTextBoxColumn();
                //createtime.HeaderText = "创建时间";
                //createtime.Width = 150;
                //createtime.DataPropertyName = "CreateTime";
                //createtime.SortMode = DataGridViewColumnSortMode.NotSortable;
                //printlistbox.Columns.Add(createtime);
                //printlistbox.RowTemplate.Height = 30;
                printlistbox.Dock = DockStyle.Fill;
                printlistbox.BorderStyle = BorderStyle.None;
                //printlistbox.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
                //printlistbox.EnableHeadersVisualStyles = false;
                //printlistbox.AutoGenerateColumns = false;
                //printlistbox.RowHeadersVisible = false;
                //printlistbox.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                //printlistbox.AllowUserToAddRows = false;  // 禁用添加新行
                //printlistbox.AllowUserToDeleteRows = false;  // 禁用删除行
                //printlistbox.EditMode = DataGridViewEditMode.EditProgrammatically;  // 禁用单元格编辑
                //printlistbox.EnableHeadersVisualStyles = false;
                //printlistbox.ColumnHeadersDefaultCellStyle.SelectionBackColor = printlistbox.ColumnHeadersDefaultCellStyle.BackColor;
                //printlistbox.ColumnHeadersDefaultCellStyle.SelectionForeColor = printlistbox.ColumnHeadersDefaultCellStyle.ForeColor;
                //printlistbox.AllowUserToResizeRows = false;

                //printlistbox.ColumnHeadersHeight = 25;
                //printlistbox.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;


                TabPage tabprint = new TabPage();
                tabprint.Text = item.Name;
                tabprint.Name = item.Name;
                tabprint.Controls.Add(printlistbox);
                printlistbox.ColumnsBrushColor = Color.Gray;
                printlistbox.ColumnsBrushColor = Color.White;
                printlistbox.RowHeight = 35;
                printlistbox.MaxRowCount = 200;
                _PrintTaskList.TabPages.Add(tabprint);
                _listviewMap[item.Name] = printlistbox;
            }
            YB.PrintTask.SetPrintEd(PrintEd);


            YB.Log.Write("初始化用户登录功能");
            //初始化用户登录
            YB.User.BindLogin(LoginUser);
            JObject userconfig = YB.User.GetConfig();
            bool rememberpassword = false;
            Config.ReadJObject<bool>(userconfig, "RememberPassword", ref rememberpassword);
            rememberPassword.Checked = rememberpassword;
            string usernamestr = "";
            Config.ReadJObject<string>(userconfig, "SaveUserName", ref usernamestr);
            username.Text = usernamestr;
            string userpassstr = "";
            Config.ReadJObject<string>(userconfig, "SaveUserPassword", ref userpassstr);
            password.Text = userpassstr;
            string userserverurl = "";
            Config.ReadJObject<string>(userconfig, "Host", ref userserverurl);
            UserLoginServerUrl.Text = userserverurl;
            bool autologin = false;
            Config.ReadJObject<bool>(userconfig, "AutoLogin", ref autologin);
            AutoLogin.Checked = autologin;


            //初始化电子秤设置
            string[] comlist = YB.ElectronicScale.GetComList();
            for (int i = 0; i < comlist.Length; i++)
            {
                ComList.Items.Add(comlist[i]);
            }
            JObject esdata = YB.ElectronicScale.GetConfig();
            string comname = "";
            Config.ReadJObject<string>(esdata, "ComName", ref comname);
            ComList.Text = comname;
            int bts = 0;
            Config.ReadJObject<int>(esdata, "Bts", ref bts);
            Bits.Value = bts;
            YB.ElectronicScale.BindOnChange(weightOnChange);
            YB.ElectronicScale.Bgen();

            YB.Log.Write("初始化WebSocket");
            //初始化WebSocket参数
            WebSocketConfig = YB.WebSocket.GetConfig();
            string wsport = "9696";
            YB.Config.ReadJObject<string>(WebSocketConfig, "wsPort", ref wsport);
            wsPort.Text = wsport;
            string wssport = "9797";
            YB.Config.ReadJObject<string>(WebSocketConfig, "wssPort", ref wssport);
            wssPort.Text = wssport;
            YB.Log.Write("初始化WebServer");
            //初始化Http服务器
            WebConfig = YB.WebServer.GetConfig();
            string IP = textBox1.Text;
            YB.Config.ReadJObject<string>(WebConfig, "Ip", ref IP);
            textBox1.Text = IP;
            string Port = textBox2.Text;
            YB.Config.ReadJObject<string>(WebConfig, "Port", ref Port);
            textBox2.Text = Port;
            YB.WebServer.SetPostRun(RunPost);
            YB.WebServer.Start();
            //启动WebSocket服务
            YB.WebSocket.BindCommand("recordstatr", RecordScreen);
            YB.WebSocket.BindCommand("stoprecord", StopRecord);
            YB.WebSocket.BindCommand("recorddesktop", RecordScreen);
            YB.WebSocket.BindCommand("stoprecorddesktop", StopRecord);
            YB.WebSocket.BindCommand("getPrinters", getPrinters);
            YB.WebSocket.BindCommand("printtag", PrintTag);//绑定打印标签过程
            YB.WebSocket.BindCommand("printdb", PrintDb);//绑定打印配货单过程
            YB.WebSocket.BindCommand("printexp", PrintExp);//绑定打印快递单过程
            YB.WebSocket.BindCommand("GetVersion", GetVersion);
            YB.WebSocket.BindCommand("gotoplug", GotoPlug);
            YB.WebSocket.BindCommand("makeexcel", MakeExcel);
            YB.WebSocket.BindCommand("playmp3", PlayMp3);
            YB.WebSocket.BindCommand("message_volume", PlayAcc);
            YB.WebSocket.Start();
            YB.Log.Write("启动成功");
            //开始初始化打印组件管理
            InitPrintPlug();
            //最后执行用户登录
            JObject switchweightdata = Config.ReadConfig("switchweight");
            bool switchweightbool = false;
            Config.ReadJObject<bool>(switchweightdata, "switchweight", ref switchweightbool);
            switchweight.Checked = switchweightbool;
            YB.Log.Write("正在初始化用户，或者进行用户登录");
            YB.User.Init(runOver);
        }
        void runOver()
        {
            loadOver = true;
        }
        void RunPost(Dictionary<string, object> data, System.Net.HttpListenerResponse r)
        {
            if (data.ContainsKey("command"))
            {
                switch (data["command"])
                {
                    case "package":
                        //打包发货接口
                        string billno = YB.Cast.ToString(data["code"]);
                        int weight = YB.Cast.ToInt(data["weight"]);
                        string machineid = YB.Cast.ToString(data["machineid"]);
                        billno = MachLogisticsCode(billno);
                        if (uniqueDictionary.Contains(billno))
                        {
                            return;
                        }
                        else
                        {
                            uniqueDictionary.Add(billno, true);
                            if (uniqueDictionary.Count > 10)
                            {
                                uniqueDictionary.RemoveAt(uniqueDictionary.Count - 10);
                            }
                        }
                        if (billno == "" || billno == string.Empty)
                        {
                            PlayAudio(AudioMap["billnoempty"]);
                            r.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                            r.StatusDescription = "单号缺失";
                            r.OutputStream.Close();
                            return;
                        }
                        if (weight == 0)
                        {
                            selectWeightType.Invoke((Action)(() =>
                            {
                                switch (selectWeightType.SelectedValue.ToString())
                                {
                                    case "1":
                                        if (WeightInput.Text == "")
                                        {
                                            weight = 0;
                                        }
                                        else
                                        {
                                            weight = int.Parse(WeightInput.Text);
                                        }
                                        break;
                                    case "2":
                                        if (WeightInput.Text == "")
                                        {
                                            weight = 0;
                                        }
                                        else
                                        {
                                            weight = int.Parse(WeightInput.Text);
                                        }
                                        break;
                                }
                                PostBillNo(billno, weight);
                                r.StatusCode = (int)System.Net.HttpStatusCode.OK;
                                r.ContentType = "text/plain";
                                JObject outData = new JObject();
                                outData["state"] = "ok";
                                byte[] outByte = Encoding.UTF8.GetBytes(outData.ToString());
                                r.OutputStream.Write(outByte, 0, outByte.Length);
                                r.OutputStream.Close();
                            }));
                        }
                        else
                        {
                            PostBillNo(billno, weight);
                            r.StatusCode = (int)System.Net.HttpStatusCode.OK;
                            r.ContentType = "text/plain";
                            JObject outData = new JObject();
                            outData["state"] = "ok";
                            byte[] outByte = Encoding.UTF8.GetBytes(outData.ToString());
                            r.OutputStream.Write(outByte, 0, outByte.Length);
                            r.OutputStream.Close();
                        }
                        break;
                    default:
                        r.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                        r.StatusDescription = "无此接口";
                        r.OutputStream.Close();
                        break;
                }
            }
            else
            {
                r.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                r.StatusDescription = "无此接口";
                r.OutputStream.Close();
            }
        }
        void SendMsg(IWebSocketConnection socket, int code, string cmd, string msg, string state = "", JObject data = null)
        {
            if (socket == null)
            {
                return;
            }
            try
            {
                SocketReturn outdata = new SocketReturn();
                outdata.Cmd = cmd;
                outdata.Code = code;
                outdata.State = state;
                outdata.Status = state;
                outdata.Msg = msg;
                if (data != null)
                {
                    outdata.Data = data;
                }
                string returntext = outdata.ToString();
                socket.Send(returntext);
            }
            catch (Exception ex)
            {
                YB.Log.Write("发送信息给客户端错误[" + ex.ToString() + "]");
            }
        }
        bool MakeExcel(SocketCommand command, JObject olddata, IWebSocketConnection socket)
        {
            //Console.WriteLine("makeexcel"+ olddata.ToString());
            if (olddata["data"] != null)
            {
                JObject data = olddata["data"].ToObject<JObject>();
                if (data.ContainsKey("Type") && data.ContainsKey("Sn"))
                {
                    string sn = data["Sn"].ToString();
                    switch (data["Type"].ToString())
                    {
                        case "new":
                            if (!excelMap.ContainsKey(sn))
                            {
                                excelMap.Add(sn, new YbMakeExcel());
                                if (data["SheetName"] != null)
                                {
                                    excelMap[sn].AddSheet(data["SheetName"].ToString());
                                }
                            }
                            break;
                        case "newsheet":
                            if (excelMap.ContainsKey(sn))
                            {
                                excelMap[sn].SelectSheet(data["SheetName"].ToString());
                            }
                            break;
                        case "biaotou":
                            if (excelMap.ContainsKey(sn))
                            {
                                List<YbMakeExcel.CaptionData> captiontoken = data["Data"].ToObject<List<YbMakeExcel.CaptionData>>();
                                if (captiontoken != null)
                                {
                                    Console.WriteLine(JsonConvert.SerializeObject(data["Data"]));
                                    Console.WriteLine(JsonConvert.SerializeObject(captiontoken));
                                    excelMap[sn].SetCaption(captiontoken);
                                    //Console.WriteLine("设置表头");
                                }
                            }
                            break;
                        case "neirong":
                            if (excelMap.ContainsKey(sn))
                            {
                                JArray rowdata = data["Data"].ToObject<JArray>();
                                if (rowdata != null)
                                {
                                    excelMap[sn].AddRow(rowdata);
                                    //Console.WriteLine("添加内容");
                                }
                            }
                            break;
                        case "end":
                            if (excelMap.ContainsKey(sn))
                            {
                                thisForm.Invoke((Action)(() =>
                                {
                                    PlayAudio(AudioMap["bgendownload"]);
                                    thisForm.TopMost = true;
                                    SaveFileDialog openFileDialog = new SaveFileDialog();
                                    openFileDialog.Filter = "XLSX文件|*.xlsx"; // 设置过滤器，仅显示可执行文件和所有文件
                                    openFileDialog.InitialDirectory = FFmpegPath.Text;
                                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                                    {
                                        string selectedFile = openFileDialog.FileName;
                                        try
                                        {
                                            using (FileStream fileStream = new FileStream(selectedFile, FileMode.Create))
                                            {
                                                excelMap[sn].MakeExcelFile(fileStream);
                                                excelMap.Remove(sn);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show("文件被占用：" + ex.Message, "保存文件错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                        }

                                    }
                                    else
                                    {
                                        excelMap.Remove(sn);
                                    }
                                    thisForm.TopMost = false;
                                }));
                            }
                            break;
                    }
                }
            }
            return true;
        }
        bool GotoPlug(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            thisForm.Invoke((Action)(() =>
            {
                if (data == null)
                {
                    SendMsg(socket, 8001, "gotoplug", "传递的参数错误data为空", "error");
                }
                //Console.WriteLine(data.ToString());
                string printname = YB.PrintTask.GetDefaultPrintName();
                Config.ReadJObject<string>(data, "printName", ref printname);
                string kind = "";
                string uid = "";
                Config.ReadJObject<string>(data, "sendUid", ref uid);
                string uidkind = "";
                Config.ReadJObject<string>(data, "sendKind", ref uidkind);
                Config.ReadJObject<string>(data, "kind", ref kind);
                if (kind == "")
                {
                    SendMsg(socket, 8001, "gotoplug", "没有传送组件类型", "error");
                }
                string senddata = "";
                Config.ReadJObject<string>(data, "message", ref senddata);
                if (senddata == "")
                {
                    SendMsg(socket, 8001, "gotoplug", "没有发送组件必须信息", "error");
                }
                var err = Printlist.AddNewPrint(printname, kind, uid, uidkind, senddata, socket);
                if (err != null)
                {
                    SendMsg(socket, 8001, "gotoplug", "转发失败[" + err.Error + "]", "error");
                }
            }));

            return true;
        }
        bool GetVersion(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            Assembly assembly = Assembly.GetEntryAssembly();
            // 获取当前程序集的版本号
            Version version = assembly.GetName().Version;
            string versionNumber = version.ToString();
            SocketReturn outdata = new SocketReturn();
            outdata.Cmd = "YbGetVersion";
            outdata.Code = 2;
            outdata.State = "OK";
            outdata.Status = "OK";
            outdata.Msg = versionNumber;
            string returntext = outdata.ToString();
            socket.Send(returntext);
            return true;
        }
        void PrintEd(string printName, string data)
        {
            if (PrintTab.InvokeRequired)
            {
                PrintTab.Invoke(new Action<string, string>(PrintEd), printName, data);
            }
            else
            {
                if (PrintTab.TabPages.ContainsKey(printName))
                {
                    ListBox listBox = (ListBox)PrintTab.TabPages[printName].Controls[0];
                    listBox.Items.Insert(0, data);
                    // 其他操作
                }
                else
                {
                    // 处理找不到指定标签的情况
                    YB.Log.Write("找不到打印机列表[" + printName + "]，如果是新增了打印机，请刷新打印机");
                }
            }
        }
        void ProgressChangeFun(int p)
        {
            if (ProgressChange.InvokeRequired)
            {
                ProgressChange.Invoke(new Action<int>(ProgressChangeFun), p);
            }
            else
            {
                ProgressChange.Text = p.ToString();
            }
        }
        private void ChangeWeightType(object sender, EventArgs e)
        {
            try
            {
                JObject DZC = YB.Config.ReadConfig("DZC");
                if (DZC == null)
                {
                    DZC = new JObject();
                }
                string thisvalue = selectWeightType.SelectedValue.ToString();
                int selectindex = int.Parse(thisvalue);
                if (DZC.ContainsKey("WeightType"))
                {
                    DZC.Remove("WeightType");
                }
                DZC.Add("WeightType", thisvalue);
                YB.Config.WriteConfig("DZC", DZC);
            }
            catch (Exception ex)
            {

            }
            if (selectWeightType.SelectedValue.ToString() == "1")
            {
                float weight = 0;
                float.TryParse(StockOutWeight.Text, out weight);
                if (!switchweight.Checked)
                {
                    weight = weight * 1000;
                }
                WeightInput.Text = weight.ToString();
            }
            else
            {
                WeightInput.Text = "";
            }
        }
        private void ChangeWeightDw(object sender, EventArgs e)
        {
            if (selectWeightType.SelectedValue.ToString() == "1")
            {
                float weight = 0;
                float.TryParse(StockOutWeight.Text, out weight);
                if (!switchweight.Checked)
                {
                    weight = weight * 1000;
                }
                WeightInput.Text = weight.ToString();
            }
            else
            {
                WeightInput.Text = "";
            }
            JObject savedata = new JObject();
            savedata["switchweight"] = switchweight.Checked;
            Config.WriteConfig("switchweight", savedata);
        }
        private void FillinWeight(object sender, EventArgs e)
        {
            if (selectWeightType.SelectedValue.ToString() == "1")
            {
                if (WeightInput.InvokeRequired)
                {
                    WeightInput.Invoke(new Action<object, EventArgs>(FillinWeight));
                }
                else
                {
                    System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
                    float weight = 0;
                    float.TryParse(label.Text, out weight);
                    if (!switchweight.Checked)
                    {
                        weight = weight * 1000;
                    }
                    WeightInput.Text = weight.ToString();
                }
            }
        }
        void weightOnChange(float weight)
        {
            if (nowWeight.InvokeRequired)
            {
                nowWeight.Invoke(new Action<float>(weightOnChange), weight);
            }
            else
            {
                nowWeight.Text = weight.ToString();
            }
            if (StockOutWeight.InvokeRequired)
            {
                StockOutWeight.Invoke(new Action<float>(weightOnChange), weight);
            }
            else
            {
                StockOutWeight.Text = weight.ToString();
            }
        }

        //开始录像的指令
        bool RecordScreen(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            var err = YB.FFmpeg.StartRecord(command.RequestID);
            if (err != null)
            {
                if (socket != null)
                {
                    SocketReturn outdata = new SocketReturn();
                    outdata.Cmd = "recorddesktop";
                    outdata.Code = err.Code;
                    outdata.State = "ERROR";
                    outdata.Status = "ERROR";
                    outdata.Msg = err.Error;
                    string returntext = outdata.ToString();
                    socket.Send(returntext);
                }
            }
            else
            {
                if (socket != null)
                {
                    SocketReturn outdata = new SocketReturn();
                    outdata.Cmd = "recorddesktop";
                    outdata.Code = 0;
                    outdata.State = "OK";
                    outdata.Status = "OK";
                    outdata.Msg = "已经开始录像";
                    string returntext = outdata.ToString();
                    socket.Send(returntext);
                }
            }
            return true;
        }
        bool PrintExp(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            if (data.ContainsKey("order"))
            {
                string printName = YB.PrintTask.GetDefaultPrintName();
                Config.ReadJObject<string>(data, "printname", ref printName);
                var datanode = data.SelectToken("order");
                if (datanode is JArray)
                {
                    foreach (var item in datanode.ToObject<JArray>())
                    {
                        JObject thisobj = item.ToObject<JObject>();
                        string templateurl = "";
                        Config.ReadJObject(thisobj, "TemplateUrl", ref templateurl);
                        string ids = "";
                        Config.ReadJObject<string>(thisobj, "requestID", ref ids);
                        if (templateurl != "")
                        {
                            var Template = YB.PrintTask.GetTemplateByUrl(templateurl);
                            if (Template != null)
                            {
                                YB.PrintTask.AddNewPrintTask(printName, ids, Template, thisobj);
                            }
                        }
                        else
                        {
                            SocketReturn outdataa = new SocketReturn();
                            outdataa.Cmd = "printexp";
                            outdataa.Code = 2002;
                            outdataa.State = "Error";
                            outdataa.Status = "Error";
                            outdataa.Msg = "打印模板没有设置，无法打印";
                            socket.Send(outdataa.ToString());
                        }
                    }
                }
                SocketReturn outdata = new SocketReturn();
                outdata.Cmd = "printexp";
                outdata.Code = 0;
                outdata.State = "OK";
                outdata.Status = "OK";
                outdata.Msg = "已经添加到打印通道中";
                string returntext = outdata.ToString();
                socket.Send(returntext);

            }
            return true;
        }
        bool PlayAcc(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            try
            {
                string filedata = "";
                Config.ReadJObject<string>(data, "Data", ref filedata);
                if (filedata != "")
                {
                    byte[] file = Convert.FromBase64String(filedata);
                    file = DecompressGzip(file);
                    Playacc(file);
                }
            }catch (Exception ex)
            {

            }
            return true;
        }
        bool PlayMp3(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            return true;
        }
        //获得打印机列表指令
        bool PrintDb(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            if (data.ContainsKey("dborder"))
            {
                string printName = YB.PrintTask.GetDefaultPrintName();
                Config.ReadJObject<string>(data, "printname", ref printName);
                string templateurl = "";
                Config.ReadJObject(data, "dborder.TemplateUrl", ref templateurl);
                string ids = "";
                Config.ReadJObject<string>(data, "requestID", ref ids);
                if (templateurl != "")
                {
                    var Template = YB.PrintTask.GetTemplateByUrl(templateurl);
                    var datanode = data.SelectToken("dborder");
                    if (datanode is JArray)
                    {
                        foreach (var item in datanode.ToObject<JArray>())
                        {
                            YB.PrintTask.AddNewPrintTask(printName, ids, Template, item.ToObject<JObject>());
                        }
                    }
                    else
                    {
                        YB.PrintTask.AddNewPrintTask(printName, ids, Template, data["dborder"].ToObject<JObject>());
                    }
                }
            }
            return true;
        }
        bool PrintTag(SocketCommand command, JObject data, IWebSocketConnection socket)
        {

            if (data.ContainsKey("dborder"))
            {
                string printName = YB.PrintTask.GetDefaultPrintName();
                Config.ReadJObject<string>(data, "printname", ref printName);
                string templateurl = "";
                Config.ReadJObject(data, "dborder.TemplateUrl", ref templateurl);
                string ids = "";
                Config.ReadJObject<string>(data, "requestID", ref ids);
                ids += DateTime.Now.ToString();
                int printnum = 1;
                Config.ReadJObject<int>(data, "dborder.Order.PrintNum", ref printnum);
                if (templateurl != "")
                {
                    var Template = YB.PrintTask.GetTemplateByUrl(templateurl);
                    var datanode = data.SelectToken("dborder.Tags");
                    if (datanode is JArray)
                    {
                        int idindex = 0;
                        foreach (var item in datanode.ToObject<JArray>())
                        {
                            idindex++;
                            YB.PrintTask.AddNewPrintTask(printName, ids + "-" + idindex.ToString(), Template, item.ToObject<JObject>(), "打印标签", printnum);
                        }
                    }
                    else
                    {
                        YB.PrintTask.AddNewPrintTask(printName, ids, Template, data["dborder.Tags"].ToObject<JObject>(), "打印标签", printnum);
                    }

                }
            }
            return true;
        }
        bool getPrinters(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            var printlist = YB.PrintTask.GetPrintList();

            string defp = YB.PrintTask.GetDefaultPrintName();
            if (socket != null)
            {
                SocketReturn outdata = new SocketReturn();
                outdata.Cmd = "getprinters";
                outdata.Code = 0;
                outdata.State = "OK";
                outdata.Status = "OK";
                outdata.Msg = "当前系统打印机列表";
                outdata.DefaultPrinter = defp;
                outdata.Printers = printlist;
                string returntext = outdata.ToString();
                socket.Send(returntext);

            }
            //}
            return true;
        }
        //停止录像的指令
        bool StopRecord(SocketCommand command, JObject data, IWebSocketConnection socket)
        {
            var err = YB.FFmpeg.StopRecord();
            //if (err != null)
            //{
            //    SocketReturn outdata = new SocketReturn();
            //    outdata.Cmd = "recorddesktop";
            //    outdata.Code = err.Code;
            //    outdata.State = "ERROR";
            //    outdata.Status = "ERROR";
            //    outdata.Msg = err.Error;
            //    string returntext = outdata.ToString();
            //    socket.Send(returntext);
            //}
            //else
            //{
            if (socket != null)
            {
                SocketReturn outdata = new SocketReturn();
                outdata.Cmd = "recorddesktop";
                outdata.Code = 0;
                outdata.State = "STOP";
                outdata.Status = "STOP";
                outdata.Msg = "已经停止录像";
                string returntext = outdata.ToString();
                socket.Send(returntext);
            }
            //}
            return true;
        }
        public static void ShowPrintLog(string printname)
        {
            thisForm.Invoke((Action)(() =>
            {
                thisForm.WindowState = FormWindowState.Normal;
                thisForm.Opacity = 1D;
                thisForm.ShowInTaskbar = true;
                thisForm.Visible = true;
                MainTabControl.SelectedIndex = 4;
                for (int i = 0; i < _PrintTaskList.TabCount; i++)
                {
                    if (_PrintTaskList.TabPages[i].Text == printname)
                    {
                        _PrintTaskList.SelectedIndex = i;
                        break;
                    }
                }
            }));
        }
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (loadOver)
            {
                this.WindowState = FormWindowState.Normal;
                this.Opacity = 1D;
                this.ShowInTaskbar = true;
                this.Visible = true;
            }
        }
        private void main_Closing(object sender, FormClosingEventArgs e)
        {
            // 阻止窗口关闭  
            this.WindowState = FormWindowState.Minimized;
            e.Cancel = true;
            this.ShowInTaskbar = false;
            // 隐藏窗口  
            this.Visible = false;
        }

        private void main_Shown(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void 在线帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            YB.Base.OpenUrl("https://www.jxos.cn/jxkc");
        }

        private void startRecord_Click(object sender, EventArgs e)
        {
            SocketCommand command = new SocketCommand();
            command.RequestID = "test";
            RecordScreen(command, null, null);
            MessageBox.Show("已经发送录像指令", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
        }

        private void stopRecordButton_Click(object sender, EventArgs e)
        {
            StopRecord(null, null, null);
            MessageBox.Show("已经停止路线", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
        }

        private void seleftfolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();

            // 设置对话框的起始路径
            string savepath = @"C:\";
            if (SaveFilePath.Text != "")
            {
                savepath = SaveFilePath.Text;
            }
            folderDialog.SelectedPath = savepath;
            // 显示对话框并获取用户选择的文件夹路径
            DialogResult result = folderDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                // 用户选择了文件夹，可以获取选中文件夹的路径
                string selectedFolderPath = folderDialog.SelectedPath;
                SaveFilePath.Text = selectedFolderPath;
            }

        }

        private void saveFFmpegConfig_Click(object sender, EventArgs e)
        {
            JObject saveData = new JObject();
            saveData["Parameter"] = Parameter.Text;
            saveData["FFmpegPath"] = FFmpegPath.Text;
            saveData["SaveFilePath"] = SaveFilePath.Text;
            saveData["AutioDriver"] = AutioDriver.Text;
            saveData["DiskMinSize"] = (long)DiskMinSize.Value;
            saveData["AutoDelFile"] = AutoDelFile.Checked;
            saveData["AutoUpdateFile"] = AutoUpdateFile.Checked;
            saveData["UploadServerUrl"] = UploadServerUrl.Text;
            saveData["MaxRecodTime"] = MaxRecodTime.Value;
            YB.FFmpeg.SetConfig(saveData);
            if (AutoUpdateFile.Checked)
            {
                YB.FFmpeg.BgenUpLoadFile();
            }
            else
            {
                YB.FFmpeg.CancelUploadTimer();
            }
            MessageBox.Show("保存完成", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
        }

        private void selectFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "FFmpeg文件|ffmpeg.exe|All Files|*.*"; // 设置过滤器，仅显示可执行文件和所有文件
            openFileDialog.InitialDirectory = FFmpegPath.Text;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedFile = openFileDialog.FileName;
                FFmpegPath.Text = selectedFile;
            }
        }
        public void Logout()
        {
            if (MainTabControl != null)
            {
                MainTabControl.Invoke((Action)(async () =>
                {
                    loginbox.Visible = true;
                    userinfobox.Visible = false;
                    logoutbutton.Visible = false;
                }));

            }
        }
        private void runssecommand(string command, string message)
        {
            try
            {
                switch (command)
                {
                    case "playacc":
                        if (message != "")
                        {
                            Console.WriteLine(message);
                            byte[] file = Convert.FromBase64String(message);
                            file = DecompressGzip(file);
                            Playacc(file);
                        }
                        break;
                    case "showmsgbox":
                        try
                        {
                            SseClient.WmsSseMessage thismessage = JsonConvert.DeserializeObject<SseClient.WmsSseMessage>(message);
                            switch (thismessage.Kind.ToLower())
                            {
                                case "error":
                                    MessageBox.Show(thismessage.Content, thismessage.Title, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                    break;
                                case "warning":
                                    MessageBox.Show(thismessage.Content, thismessage.Title, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                                    break;
                                default:
                                    MessageBox.Show(thismessage.Content, thismessage.Title, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                        break;
                    case "sendprintdata":
                        JObject maindata = JsonConvert.DeserializeObject<JObject>(message);
                        JObject send_data = JObject.Parse(maindata["data"].ToString());
                        string printname = YB.PrintTask.GetDefaultPrintName();
                        Config.ReadJObject<string>(send_data, "printName", ref printname);
                        string kind = "";
                        Config.ReadJObject<string>(send_data, "kind", ref kind);
                        string send_mdata = "";
                        Config.ReadJObject<string>(send_data, "message", ref send_mdata);
                        if (send_mdata == "")
                        {
                            return;
                        }
                        string sendUid = "";
                        string sendKind = "";
                        Config.ReadJObject<string>(send_data, "sendUid", ref sendUid);
                        Config.ReadJObject<string>(send_data, "sendKind", ref sendKind);
                        JObject printcommand = new JObject();
                        printcommand.Add("cmd", "gotoplug");
                        printcommand.Add("kind", kind);
                        printcommand.Add("sendUid", sendUid);
                        printcommand.Add("sendKind", sendKind);
                        printcommand.Add("printName", printname);
                        printcommand.Add("message", send_mdata);
                        GotoPlug(null, printcommand, null);
                        break;
                    case "getprintlist"://获得打印机列表
                        Console.WriteLine("返回打印机列表");
                        var printlist = YB.PrintTask.GetPrintList();

                        mainStockData msg = new mainStockData();
                        msg.Command = "getprinters";
                        msg.Data = JsonConvert.SerializeObject(printlist);
                        postssecommand(msg);
                        break;
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void postssecommand(Object data)
        {
            Dictionary<string, object> postData = new Dictionary<string, object>();
            postData["Data"] = JsonConvert.SerializeObject(data);
            YbWeb.Post(User.GetHostUrl() + "/wmsapi/getinfo", "ssecommand", postData);
        }
        private void runsocketcommand(string message)
        {
            JObject data = JObject.Parse(message);
            if (data.ContainsKey("type"))
            {
                JToken typetoken = data["type"];
                string thistype = typetoken.ToString();
                if (data.ContainsKey("Sn"))
                {
                    string Sn = data["Sn"].ToString();
                    if (Sn != "")
                    {
                        JObject sndeng = new JObject();
                        sndeng.Add("Sn", Sn);
                        string sendstr = JsonConvert.SerializeObject(sndeng);
                        if (_mainSocket != null)
                        {
                            _mainSocket.Send(sendstr);
                        }
                    }
                }
                Console.WriteLine("命令" + thistype);
                switch (thistype)
                {
                    case "pong":
                        if (socketOverTime != null)
                        {
                            socketOverTime.Stop();
                            socketOverTime.Dispose();
                            socketOverTime = new System.Timers.Timer(22000);
                            socketOverTime.Elapsed += socketover;
                            socketOverTime.Start();
                            //Log.Write("收到服务器Pong，重设超时函数");
                        }
                        break;
                    case "logout":
                        //被挤掉线
                        YB.User.Logout(Logout);
                        if (!rememberPassword.Checked)
                        {
                            username.Text = "";
                            password.Text = "";
                            YB.User.SetConfig("", "", "*", "*", null, false);
                        }
                        if (mainsseclient != null)
                        {
                            mainsseclient.Stop();
                            mainsseclient = null;
                        }
                        if (_mainSocket != null)
                        {
                            socketToken = "";
                            _mainSocket.Close(CloseStatusCode.Away);
                            _mainSocket = null;
                        }
                        if (MainTabControl != null)
                        {
                            MainTabControl.Invoke((Action)(async () =>
                            {
                                string logoutmsg = "此账号在另一个打印组件中登录";
                                JToken errmsg = data["data"];
                                if (errmsg != null)
                                {
                                    logoutmsg = errmsg.ToString();
                                }
                                MessageBox.Show(logoutmsg, "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            }));
                        }

                        break;
                    case "sendprintdata"://打印快递单
                        //Log.Write("收到打印快递单消息" + e.Data);

                        JObject maindata = JsonConvert.DeserializeObject<JObject>(message);
                        JObject send_data = JObject.Parse(maindata["data"].ToString());
                        string printname = YB.PrintTask.GetDefaultPrintName();
                        Config.ReadJObject<string>(send_data, "printName", ref printname);
                        string kind = "";
                        Config.ReadJObject<string>(send_data, "kind", ref kind);
                        string send_mdata = "";
                        Config.ReadJObject<string>(send_data, "message", ref send_mdata);
                        if (send_mdata == "")
                        {
                            return;
                        }
                        string sendUid = "";
                        string sendKind = "";
                        Config.ReadJObject<string>(send_data, "sendUid", ref sendUid);
                        Config.ReadJObject<string>(send_data, "sendKind", ref sendKind);
                        JObject printcommand = new JObject();
                        printcommand.Add("cmd", "gotoplug");
                        printcommand.Add("kind", kind);
                        printcommand.Add("sendUid", sendUid);
                        printcommand.Add("sendKind", sendKind);
                        printcommand.Add("printName", printname);
                        printcommand.Add("message", send_mdata);
                        GotoPlug(null, printcommand, null);
                        break;
                    case "userlist"://客户端列表
                        break;
                    case "getprintlist"://获得打印机列表
                        try
                        {
                            if (_mainSocket != null)
                            {
                                Console.WriteLine("返回打印机列表");
                                var printlist = YB.PrintTask.GetPrintList();

                                mainStockData msg = new mainStockData();
                                msg.Command = "getprinters";
                                msg.Data = JsonConvert.SerializeObject(printlist);
                                string senddata = JsonConvert.SerializeObject(msg);
                                _mainSocket.Send(senddata);
                            }

                        }
                        catch (Exception ex)
                        {

                        }

                        break;
                }
            }
        }
        async private void onmessage(Object sender, MessageEventArgs e)
        {
            if (e != null && e.Data != null)
            {
                runsocketcommand(e.Data);
            }
        }
        private void sendMsg(Object msg)
        {
            string jsonstr = JsonConvert.SerializeObject(msg);
            if (jsonstr != null && jsonstr != "")
            {
                _mainSocket.Send(jsonstr);
            }
        }
        private System.Timers.Timer socketPing;
        private System.Timers.Timer socketOverTime;
        private static readonly object socketlockObject = new object();
        private void socketping(Object source, ElapsedEventArgs e)
        {
            //lock (socketlockObject)
            //{
            if (_mainSocket != null)
            {
                JObject ping = new JObject();
                ping.Add("Command", "ping");
                string jsonstr = JsonConvert.SerializeObject(ping);
                //Log.Write("发送Socket心跳指令");
                _mainSocket.Send(jsonstr);
            }
            //}
        }
        private void socketover(Object source, ElapsedEventArgs e)
        {
            //lock (socketlockObject)
            //{
            YB.Log.Write("socket心跳超时，正在重新连接");
            socketOnline = false;
            userAvatar.Invoke((Action)(async () =>
            {
                if (mainAvatar != null)
                {
                    userAvatar.Image = YB.Base.ConvertToCircularAvatar(YB.Base.ConvertToGrayscale((Bitmap)mainAvatar));
                }
            }));
            socketOverTime.Stop();
            socketOverTime.Dispose();
            socketPing.Stop();
            socketPing.Dispose();
            _mainSocket.OnOpen -= onopen;
            _mainSocket.OnMessage -= onmessage;
            _mainSocket.OnClose -= onclose;
            _mainSocket.OnError -= onerror;

            _mainSocket = null;
            initsocket();
            //}
        }
        private void relinkSocket()
        {

        }
        private void onopen(Object sender, EventArgs e)
        {
            try
            {
                if (socketOverTime != null)
                {
                    socketOverTime.Stop();
                    socketOverTime.Dispose();
                }
                if (socketPing != null)
                {
                    socketPing.Stop();
                    socketPing.Dispose();
                }
                socketPing = new System.Timers.Timer(10000);
                socketPing.AutoReset = true;
                socketPing.Elapsed += socketping;
                socketPing.Start();
                socketOnline = true;
                socketOverTime = new System.Timers.Timer(22000);
                socketOverTime.Elapsed += socketover;
                socketOverTime.Start();
                YB.Log.Write("socket已经连接上");
                userAvatar.Invoke((Action)(async () =>
                {
                    if (mainAvatar != null)
                    {
                        userAvatar.Image = YB.Base.ConvertToCircularAvatar((Bitmap)mainAvatar);
                    }
                }));
            }
            catch (Exception ex)
            {
                YB.Log.Write("socket的onopen函数错误" + ex.Message);
            }

        }
        private void onerror(Object sender, WebSocketSharp.ErrorEventArgs e)
        {

            string errmsg = e.Message;
            YB.Log.Write("socket发生错误" + errmsg);
        }
        private void onclose(Object sender, CloseEventArgs e)
        {
            YB.Log.Write("WebSocket closed with code: " + e.Code + ", reason: " + e.Reason);
            socketOnline = false;
            YB.Log.Write("socket被关闭，正在重连" + e.Code + "[" + e.ToString() + "]");
            userAvatar.Invoke((Action)(async () =>
            {
                if (mainAvatar != null)
                {
                    userAvatar.Image = YB.Base.ConvertToCircularAvatar(YB.Base.ConvertToGrayscale((Bitmap)mainAvatar));
                }
            }));
            if (e.Code == 1001)
            {

            }
            else if (e.Code != 1000)
            {
                _mainSocket.OnOpen -= onopen;
                _mainSocket.OnMessage -= onmessage;
                _mainSocket.OnClose -= onclose;
                _mainSocket.OnError -= onerror;

                _mainSocket = null;
                initsocket();
            }
        }
        private async void LoginUser(JObject user)
        {
            if (user != null)
            {
                thisForm.Invoke((Action)(async () =>
                {
                    loginbox.Visible = false;
                    userinfobox.Visible = true;
                    logoutbutton.Visible = true;
                    string avatarurl = "";
                    Config.ReadJObject(user, "Avatar", ref avatarurl);
                    if (avatarurl != "")
                    {
                        mainAvatar = YB.Base.GetUrlPic(avatarurl);
                        if (mainAvatar != null)
                        {
                            userAvatar.Image = YB.Base.ConvertToCircularAvatar((Bitmap)mainAvatar);

                        }
                    }
                    string userinfoname = "";
                    Config.ReadJObject(user, "UserName", ref userinfoname);
                    if (userinfoname != "")
                    {
                        userinfo_name.Text = userinfoname;
                    }

                    string uid = "";
                    Config.ReadJObject(user, "Uid", ref uid);
                    if (uid != "")
                    {
                        JObject qr = new JObject();
                        qr.Add("CodeType", "PrintPlugBind");
                        qr.Add("Id", uid);
                        qr.Add("Name", userinfoname);
                        Bitmap qrcode = YB.Base.MakeQrCode(qr.ToString(), 250, 250);
                        qrcodepic.Image = qrcode;
                    }

                    string tid = "";
                    Config.ReadJObject<string>(user, "Tid", ref tid);
                    if (tid != "")
                    {
                        FFmpeg.SetUpDate(tid);
                    }
                    if (rememberPassword.Checked)
                    {
                        YB.User.SetConfig("", "", username.Text, password.Text, null, true);
                    }
                    else
                    {
                        YB.User.SetConfig("", "", "*", "*", null, false);
                    }
                    string token = "";
                    YB.Config.ReadJObject<string>(user, "Token", ref token);
                    if (token != "")
                    {
                        YB.YbWeb.SetToken(token);
                    }
                    YB.Log.Write("用户登录成功[" + userinfoname + "]");
                    SetControlEnable(MainTabControl.TabPages[5], true);
                    socketToken = token;
                    initsocket();
                    instsselink();
                }));
                //这里开始读取服务器默认设置并更改配置
                Dictionary<string, object> postData = new Dictionary<string, object>();
                postData["group"] = "SERVER_VIDEO";
                Task<YB.returnmsg> groupdata = YbWeb.Post(User.GetHostUrl() + "/wmsapi/getinfo", "getsettinggroup", postData);
                YB.returnmsg response = await groupdata;
                if (response != null)
                {
                    if (response.Errcode != 0)
                    {
                        MessageBox.Show(response.Errmsg, "远程服务信息错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        if (response.Data != null && response.Data.Count() > 0)
                        {
                            VideoConfig[] itemlist = response.Data["Items"].ToObject<VideoConfig[]>();
                            JObject saveData = new JObject();
                            saveData["Parameter"] = Parameter.Text;
                            saveData["FFmpegPath"] = FFmpegPath.Text;
                            saveData["SaveFilePath"] = SaveFilePath.Text;
                            saveData["AutioDriver"] = AutioDriver.Text;
                            saveData["DiskMinSize"] = (long)DiskMinSize.Value;
                            saveData["AutoDelFile"] = AutoDelFile.Checked;
                            saveData["AutoUpdateFile"] = AutoUpdateFile.Checked;
                            saveData["UploadServerUrl"] = UploadServerUrl.Text;
                            saveData["MaxRecodTime"] = MaxRecodTime.Value;
                            foreach (VideoConfig item in itemlist)
                            {
                                switch (item.Key.ToUpper())
                                {
                                    case "SERVER_VIDEO_URL":
                                        //设置上传服务器地址
                                        saveData["UploadServerUrl"] = item.Value;
                                        break;
                                    case "SERVER_VIDEO_BASE":
                                        //设置启动参数
                                        _Parameterstr = item.Value;
                                        break;
                                    case "SERVER_VIDEO_MINUTE":
                                        //设置最大录像时间
                                        saveData["MaxRecodTime"] = int.Parse(item.Value);
                                        break;
                                }
                            }
                            YB.FFmpeg.SetConfig(saveData);
                            LoadFFmpegConfig();

                        }
                    }
                }
                //开始读取包装材料列表
                Task<YB.returnmsg> mlisttask = YbWeb.Post(User.GetHostUrl() + "/wmsapi/getinfo", "getmateriallist");
                YB.returnmsg mlist = await mlisttask;
                if (mlist != null)
                {
                    if (mlist.Errcode != 0)
                    {
                        MessageBox.Show(response.Errmsg, "获取包装材料错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        List<Goods> itemlist = mlist.Data.ToObject<List<Goods>>();
                        itemlist.Insert(0, new Goods("0", "[不使用包装材料]", "", ""));
                        for (int i = 0; i < itemlist.Count; i++)
                        {
                            MaterialSkuMap[itemlist[i].GoodsSn] = itemlist[i];
                        }
                        MaterialSkuList.Invoke((Action)(() =>
                        {
                            MaterialSkuList.DataSource = itemlist;
                            MaterialSkuList.DropDownWidth = 400;
                            MaterialSkuList.ValueMember = "Id";

                        }));

                    }
                }
            }
            else
            {
                YB.Log.Write("用户登录失败[" + username.Text + "]");
            }
        }
        public void instsselink()
        {
            if (mainsseclient != null)
            {
                mainsseclient.Stop();
            }
            JObject userconfig = YB.User.GetConfig();
            String userserverurl = "";
            Config.ReadJObject<string>(userconfig, "Host", ref userserverurl);
            string linkurl = MakeUrl(userserverurl, "/wmsapi/sse");
            mainsseclient = new SseClient(linkurl, socketToken);
            mainsseclient.OnMessage += sseonmessage;
            mainsseclient.OnOpen += sseonopen;
            mainsseclient.OnClose += sseonclose;
            mainsseclient.Start();
        }
        private void sseonclose()
        {
            userAvatar.Invoke((Action)(async () =>
            {
                if (mainAvatar != null)
                {
                    userAvatar.Image = YB.Base.ConvertToCircularAvatar(YB.Base.ConvertToGrayscale((Bitmap)mainAvatar));
                }
            }));
            YB.Log.Write("SSE链接已经关闭");
        }
        private void sseonopen()
        {
            userAvatar.Invoke((Action)(async () =>
            {
                if (mainAvatar != null)
                {
                    userAvatar.Image = YB.Base.ConvertToCircularAvatar((Bitmap)mainAvatar);
                }
            }));
            YB.Log.Write("SSE链接成功");
        }
        private void sseonmessage(SseClient.SseMessage data)
        {
            Console.WriteLine("收到消息:" + data.ToString());
            runssecommand(data.Event, data.Data);
        }
        private void initsocket()
        {
            if (_mainSocket != null)
            {
                _mainSocket.Connect();
            }
            else if (socketToken != "")
            {
                YB.Log.Write("正在初始化socket链接" + socketToken);
                JObject userconfig = YB.User.GetConfig();
                String userserverurl = "";
                Config.ReadJObject<string>(userconfig, "Host", ref userserverurl);
                string linkurl = GetSocketUrl(MakeUrl(userserverurl, "/wmsapi/hub"));
                _mainSocket = new WebSocketSharp.WebSocket(linkurl);
                Dictionary<String, String> header = new Dictionary<String, String>();
                header.Add("Authorization", socketToken);
                header.Add("appid", "9");
                header.Add("MachineCode", YB.Base.GetHardwareFingerprint());
                header.Add("Kind", "PrintPlug");
                header.Add("Sid", Guid.NewGuid().ToString());
                _mainSocket.CustomHeaders = header;
                _mainSocket.OnMessage += onmessage;
                _mainSocket.OnClose += onclose;
                _mainSocket.OnError += onerror;
                _mainSocket.OnOpen += onopen;
                _mainSocket.Connect();
                return;
            }
        }
        private void userloginbutton_Click(object sender, EventArgs e)
        {
            if (username.Text == "" || password.Text == "")
            {
                MessageBox.Show("请输入用户名和密码后再登录！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                username.Focus();
                return;
            }
            var err = YB.User.Login(username.Text, password.Text, LoginUser);
            if (err != null)
            {
                MessageBox.Show(err.Error, "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                YB.Log.Write("登录错误[" + err.Error + "]");
                username.Focus();
            }
        }
        private void password_KeyPass(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                userloginbutton_Click(sender, e);
            }
        }
        private void username_KeyPass(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                e.Handled = true;
                password.Focus();
            }
        }

        private void logoutbutton_Click(object sender, EventArgs e)
        {
            YB.User.Logout(Logout);
            if (!rememberPassword.Checked)
            {
                username.Text = "";
                password.Text = "";
                YB.User.SetConfig("", "", "*", "*", null, false);
            }
            if (mainsseclient != null)
            {
                mainsseclient.Stop();
                mainsseclient = null;
            }
            if (_mainSocket != null)
            {
                socketToken = "";
                _mainSocket.Close(CloseStatusCode.Normal);
                _mainSocket = null;
            }
        }

        private void userConfigSaveButton_Click(object sender, EventArgs e)
        {
            if (UserLoginServerUrl.Text == "")
            {
                MessageBox.Show("必须输入或者选择一个服务器用于登录！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                UserLoginServerUrl.Focus();
                return;
            }
            var err = YB.User.SetConfig(UserLoginServerUrl.Text, "", "*", "*", AutoLogin.Checked, null);
            if (err != null)
            {
                MessageBox.Show("保存用户设置错误[" + err.Error + "]！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("保存完成", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("退出后聚星打印录像之类的无法使用，确定要退出吗？", "警告", MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Environment.Exit(0);
            }
        }

        private void returndef_Click(object sender, EventArgs e)
        {
            Parameter.Text = _Parameterstr;
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Opacity = 1D;
            this.ShowInTaskbar = true;
            this.Visible = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (wsPort.Text == "")
            {
                MessageBox.Show("至少需要输入ws端口设置！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                wsPort.Focus();
                return;
            }
            JObject saveData = new JObject();
            saveData["wsPort"] = wsPort.Text;
            saveData["wssPort"] = wssPort.Text;
            YB.WebSocket.SetConfig(saveData);
            MessageBox.Show("保存完成", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox2.Text == "")
            {
                MessageBox.Show("必须输入IP和端口号才能保存！", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                textBox1.Focus();
                return;
            }
            YB.WebServer.SetConfig(textBox1.Text, textBox2.Text);
        }

        private void ElectronicScaleSave_Click(object sender, EventArgs e)
        {
            JObject saveData = new JObject();
            saveData["ComName"] = ComList.Text;
            saveData["Bts"] = Bits.Value;
            YB.ElectronicScale.SetConfig(saveData);
            MessageBox.Show("保存完成", "成功", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None);
        }

        private void 在线更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkUpdate(true);
        }

        private void 刷新打印机列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<YB.PrintTask.PrintListItem> printList = YB.PrintTask.GetPrintList();
            PrintTab.TabPages.Clear();
            foreach (YB.PrintTask.PrintListItem item in printList)
            {
                ListBox listBox = new ListBox();
                TabPage tab = new TabPage();
                tab.Text = item.Name;
                tab.Name = item.Name;
                tab.Controls.Add(listBox);
                listBox.Dock = DockStyle.Fill;
                PrintTab.TabPages.Add(tab);
            }
        }

        private void testPrintTask_Click(object sender, EventArgs e)
        {
            YB.PrintTask.PrintTemplate template = new PrintTask.PrintTemplate();
            string teststring = "{\"pagedata\":{\"width\":110,\"height\":180,\"customTempTop\":76.7,\"ratio\":3.76562,\"pxwidth\":414.2182,\"pxheight\":677.8116,\"bgenx\":40,\"bgeny\":20},\"nodes\":[{\"type\":\"label\",\"title\":\"横排文本\",\"x\":0,\"y\":0,\"width\":110,\"height\":11,\"text\":\"标题\",\"color\":\"#000\",\"horizontalalign\":\"center\",\"verticalalign\":\"center\",\"fontsize\":24,\"fontbold\":\"bold\",\"fontfamily\":\"微软雅黑\",\"align\":\"horizontal\",\"icon\":\"fad fa-text-width\",\"opacity\":1,\"caption\":\"\"},{\"type\":\"label\",\"title\":\"横排文本\",\"x\":0,\"y\":21,\"width\":110,\"height\":5,\"text\":\"货品名称<%=data.GoodsName%>货品类型<%=data.SkuId%>\",\"color\":\"#000\",\"horizontalalign\":\"right\",\"verticalalign\":\"top\",\"fontsize\":12,\"fontbold\":\"normal\",\"fontfamily\":\"微软雅黑\",\"align\":\"horizontal\",\"icon\":\"fad fa-text-width\",\"opacity\":1,\"caption\":\"标签类-商品名称\"},{\"type\":\"label\",\"title\":\"竖排文本\",\"x\":0,\"y\":39,\"width\":5,\"height\":50,\"text\":\"竖排文本\",\"horizontalalign\":\"left\",\"verticalalign\":\"top\",\"color\":\"#000\",\"fontsize\":12,\"fontbold\":\"normal\",\"fontfamily\":\"宋体\",\"align\":\"vertical\",\"opacity\":1,\"icon\":\"fad fa-text-height\",\"caption\":\"\"},{\"type\":\"barcode\",\"codetype\":\"\",\"title\":\"竖排条码\",\"x\":7,\"y\":39,\"width\":20,\"height\":100,\"isloading\":false,\"text\":\"<%=data.SkuId%>\",\"color\":\"#000\",\"fontsize\":12,\"align\":\"vertical\",\"icon\":\"fad fa-scanner\",\"caption\":\"标签类-规格ID\",\"hidetext\":true,\"image\":{}},{\"type\":\"barcode\",\"codetype\":\"\",\"title\":\"横排条码\",\"x\":5,\"y\":143,\"width\":100,\"height\":20,\"text\":\"<%=data.SkuId%>\",\"isloading\":false,\"color\":\"#000\",\"fontsize\":12,\"align\":\"horizontal\",\"icon\":\"fad fa-barcode\",\"caption\":\"标签类-规格ID\",\"hidetext\":false,\"image\":{}},{\"type\":\"line\",\"title\":\"横线\",\"x\":4,\"y\":34,\"width\":100,\"height\":2,\"orientation\":\"horizontal\",\"linewidth\":2,\"icon\":\"fad fa-horizontal-rule\"},{\"type\":\"line\",\"title\":\"竖线\",\"x\":100,\"y\":40,\"width\":2,\"height\":100,\"orientation\":\"vertical\",\"linewidth\":2,\"icon\":\"fad fa-grip-lines-vertical\"},{\"type\":\"table\",\"codetype\":\"\",\"title\":\"表格\",\"x\":27,\"y\":39,\"width\":71,\"height\":101,\"fontsize\":12,\"fontbold\":\"normal\",\"fontfamily\":\"微软雅黑\",\"isloading\":false,\"text\":\"<%=data.SkuList%>\",\"color\":\"#000\",\"icon\":\"fal fa-table\",\"opacity\":1,\"caption\":\"配货单信息\",\"thcenter\":true,\"autopage\":true,\"th\":\"[{\\\"title\\\":\\\"货位\\\",\\\"width\\\":10,\\\"field\\\":\\\"TidName\\\"},{\\\"title\\\":\\\"商品编码\\\",\\\"width\\\":12.390044667279225,\\\"field\\\":\\\"DBRuchName\\\"},{\\\"title\\\":\\\"商品名称\\\",\\\"width\\\":11.327802592932903,\\\"field\\\":\\\"OrderCount\\\"},{\\\"title\\\":\\\"规格名称\\\",\\\"width\\\":19.02905763194376,\\\"field\\\":\\\"OrderCount\\\"},{\\\"title\\\":\\\"数量\\\",\\\"width\\\":17.481344373569296,\\\"field\\\":\\\"CuRemark\\\"},{\\\"title\\\":\\\"分拣位置\\\",\\\"width\\\":-15.228249265725157,\\\"field\\\":\\\"CuRemark\\\"}]\"}],\"var\":\"sn91d7-1702276054254-29934\"}";
            template = JsonConvert.DeserializeObject<PrintTask.PrintTemplate>(teststring);
            JObject data = JObject.Parse("{\"GoodsName\":\"货品名字测试\",\"SkuName\":\"SKU名字测试\",\"SkuId\":\"1239873495\",\"GoodsSn\":\"s98734987\",\"SkuList\":[{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224},{\"TidName\":\"货位1\",\"DBRuchName\":\"商品编码1\",\"OrderCount\":13,\"CuRemark\":224}]}");
            YB.PrintTask.AddNewPrintTask(YB.PrintTask.GetDefaultPrintName(), "id-" + DateTime.Now.ToString(), template, data);
        }
        void loglistMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                copylogmenu.Show(loglist, e.Location);
            }

        }
        void PlugOnMessage(string data, IWebSocketConnection socket)
        {
            if (socket != null)
            {
                JObject senddata = JObject.Parse(data);
                SendMsg(socket, 0, "plugreturn", "打印组件返回消息", "SEND", senddata);
            }
        }
        public static bool IsValidJson(string strInput)
        {
            Console.WriteLine("检查的JSON字符串" + strInput);
            try
            {
                JArray.Parse(strInput);
                return true; // 没有异常，说明是有效的JSON字符串
            }
            catch (JsonReaderException)
            {
                return false; // 捕获到异常，说明不是有效的JSON字符串
            }
            catch (Exception)
            {
                // 其他类型的异常，可能是解析时发生了意外错误
                return false;
            }
        }

        async void InitPrintPlug()
        {
            Dictionary<string, object> postData = new Dictionary<string, object>();
            Task<string> mlisttask = YbWeb.DownloadText("https://www.jxwms.net/static/printplug.json");
            string response = await mlisttask;
            string plugstr = "[{\"Kind\":\"544\",\"Port\":\"9113\",\"WssPort\":\"9114\",\"Address\":\"127.0.0.1\",\"title\":\"京东组件\",\"icon\":\"jingdong\",\"type\":\"WebSocket\",\"downloadlink\":\"http://prod-oms-app-cprt.jdwl.com/OpenCloudPrint/setup.exe\"},{\"Kind\":\"548\",\"Port\":\"13528\",\"WssPort\":\"13529\",\"Address\":\"127.0.0.1\",\"title\":\"菜鸟组件\",\"icon\":\"cainiaoicon\",\"type\":\"WebSocket\",\"downloadlink\":\"https://61.160.223.183:9020/download/JXOSXZ/CNPrintSetup0.4.8.6.exe\"},{\"Kind\":\"566\",\"Port\":\"5000\",\"WssPort\":\"18653\",\"Address\":\"127.0.0.1\",\"title\":\"拼多多组件\",\"icon\":\"pddicon\",\"type\":\"WebSocket\",\"downloadlink\":\"http://meta.pinduoduo.com/api/one/app/v1/lateststable?appId=com.xunmeng.pddprint&platform=windows&subType=main\"},{\"Kind\":\"615\",\"Port\":\"13888\",\"WssPort\":\"13999\",\"Address\":\"127.0.0.1\",\"title\":\"抖音组件\",\"icon\":\"douyin\",\"type\":\"WebSocket\",\"downloadlink\":\"https://lf3-cm.ecombdstatic.com/obj/logistics-davinci/install/CloudPrintClient-1.0.4.7-beta(win).exe\"},{\"Kind\":\"633\",\"Port\":\"16888/ks/printer\",\"WssPort\":\"16889/ks/printer\",\"Address\":\"127.0.0.1\",\"title\":\"快手组件\",\"icon\":\"kuaishou\",\"type\":\"WebSocket\",\"downloadlink\":\"https://u2-401.ecukwai.com/kos/nlav11586/printer/KuaishouPrint-Setup-2.1.1.9_v1.exe\"},{\"Kind\":\"638\",\"Port\":\"12233\",\"WssPort\":\"12234\",\"Address\":\"127.0.0.1\",\"title\":\"唯品会打印组件\",\"icon\":\"vip\",\"type\":\"WebSocket\",\"downloadlink\":\"https://vos.vipstatic.com/vip-lbs-printer/printer/vip_printer_setup_0.8.38.exe\"},{\"Kind\":\"672\",\"Port\":\"12705\",\"WssPort\":\"12709\",\"Address\":\"127.0.0.1\",\"title\":\"微信视频号组件\",\"icon\":\"sphicon\",\"type\":\"WebSocket\",\"downloadlink\":\"https://res.wx.qq.com/shop/print/ChannelsShopPrintClient-setup.exe\"},{\"Kind\":\"673\",\"Port\":\"14528\",\"WssPort\":\"14529\",\"Address\":\"127.0.0.1\",\"title\":\"小红书组件\",\"icon\":\"xhsicon\",\"type\":\"WebSocket\",\"downloadlink\":\"https://xhswaybill-printer-1251524319.cos.ap-shanghai.myqcloud.com/XHPrintTool/prod/win/xiaohongshu-win.exe\"}]";
            if (IsValidJson(response))
            {
                plugstr = response;
            }
            var err = Printlist.Init(plugstr);
            if (err != null)
            {
                YB.Log.Write("初始化打印组件信息错误" + err.Error);
            }
            JArray pluglist = JArray.Parse(plugstr);
            int x = 0;
            int y = 0;
            foreach (JToken item in pluglist)
            {
                string _title = item["title"].ToString();
                string _kind = item["Kind"].ToString();
                string _address = item["Address"].ToString();
                string _port = item["Port"].ToString();
                string _downloadlink = item["downloadlink"].ToString();
                Image _imagedata = GetImageFromResources(item["icon"].ToString());
                PrintPlug plug = new PrintPlug(_title, _kind, _address, _port, _imagedata, _downloadlink);
                plug.Name = _kind;
                plug.OnMessage = PlugOnMessage;
                plug.Location = new Point(x * 75, y * 140);
                x++;
                if (x * 75 > tabControl1.TabPages[3].Width)
                {
                    x = 0;
                    y++;
                }
                AddNewPlug(plug);
            }
        }
        private void GetMaterialSku()
        {
            var header = YB.User.MakeHeader();
            var data = YB.Web.Get("http://127.0.0.1:8081/api/v1/wms/goods", header, "command", "getmdata");
            if (data.hasErr())
            {

            }
            string datastr = (string)data.Data;
            Console.WriteLine(datastr);
            //JObject list = JObject.Parse(datastr);
            //if (list != null)
            //{
            //    foreach (JToken item in list)
            //    {
            //        var name = item.SelectToken("GoodsName");
            //        var id=item.SelectToken("Id");
            //        Console.Write("包装材料" + id.ToString() + "|" + name.ToString());
            //    }
            //}
        }
        private void AddNewPlug(PrintPlug plug)
        {
            if (tabControl1.InvokeRequired)
            {
                tabControl1.Invoke(new Action<PrintPlug>(AddNewPlug), plug);
            }
            else
            {
                tabControl1.TabPages[3].Controls.Add(plug);
            }
        }
        public static Image GetImageFromResources(string resourceName)
        {
            return (Image)Properties.Resources.ResourceManager.GetObject(resourceName);
        }
        private void 打开日志目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory + "log");
        }

        private void 复制到剪贴板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (loglist.SelectedItem != null)
            {
                Clipboard.SetText(loglist.SelectedItem.ToString());
            }
        }

        private void 复制所有内容到剪贴板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (loglist.Items.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in loglist.Items)
                {
                    sb.Append(item.ToString()); sb.Append(Environment.NewLine);
                }
                Clipboard.SetText(sb.ToString());
            }
        }

        private void PrintTab_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshPrintButton();
        }
        //打印组件列表操作
        public static void UpdatePrintListTask(string printname, string id, string state)
        {

            if (_listviewMap.ContainsKey(printname))
            {
                YBListView dataGridView = _listviewMap[printname];
                // 使用委托来更新DataGridView
                PrintListView row = new PrintListView(id, state, id, "A");
                dataGridView.Update(row, "State");
            }
        }
        public static YB.errmsg AddTaskToList(string index, string printname, string kind, string id, Image icon, int ordercount = 1)
        {

            if (_listviewMap.ContainsKey(printname))
            {
                try
                {
                    YBListView dataGridView = _listviewMap[printname];
                    PrintListView row = new PrintListView(index, "排队中", id, kind);
                    row.OrderCount = ordercount;
                    row.Icon = icon;
                    dataGridView.Add(row);
                    return null;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return new YB.errmsg(1101, "添加到任务列表错误[" + ex.ToString() + "]");
                }
            }
            return new YB.errmsg(1102, "添加到任务列表错误[没有找到对应的打印机:" + printname + "]");
        }

        private void RefreshMaterialSku_Click(object sender, EventArgs e)
        {

            PopupWindow.AddNewWindow("标题" + PopupWindow.Count.ToString(), "内容", GetImageFromResources("jingdong"));
        }

        private void DbScanInputBox_KeyPress(object sender, KeyPressEventArgs e)
        {


        }
        private byte[] DecompressGzip(byte[] compressedData)
        {
            using (MemoryStream ms = new MemoryStream(compressedData))
            using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress))
            using (MemoryStream decompressedMs = new MemoryStream())
            {
                gzip.CopyTo(decompressedMs);
                return decompressedMs.ToArray();
            }
        }

        public void PlayAcc(byte[] accData)
        {
            // 创建一个临时文件
            string tempFilePath = Path.GetTempFileName() + ".aac";
            try
            {
                // 将ACC数据写入临时文件
                File.WriteAllBytes(tempFilePath, accData);

                using (var reader = new MediaFoundationReader(tempFilePath))
                {
                    // 创建一个WaveOutEvent实例来播放音频
                    using (var outputDevice = new WaveOutEvent())
                    {
                        // 初始化输出设备并播放
                        outputDevice.Init(reader);
                        outputDevice.Play();

                        // 等待播放完成，或者根据需要设置其他逻辑（例如，用户输入停止）
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(100);
                        }
                    }
                }
            }
            finally
            {
                // 删除临时文件
                File.Delete(tempFilePath);
            }
        }

        public void PlayMp3(byte[] mp3Data)
        {
            // 使用MemoryStream加载MP3数据
            using (MemoryStream ms = new MemoryStream(mp3Data))
            {
                // 创建一个Mp3FileReader来读取MP3数据
                using (Mp3FileReader reader = new Mp3FileReader(ms))
                {
                    // 创建一个WaveOutEvent来播放音频
                    using (WaveOutEvent outputDevice = new WaveOutEvent())
                    {
                        // 初始化输出设备并播放
                        outputDevice.Init(reader);
                        outputDevice.Play();

                        // 等待播放完成，或者根据需要设置其他逻辑（例如，用户输入停止）
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(100);
                        }
                    }
                }
            }
        }

        Action<byte[]> playAudio = (file) =>
        {
            using (MemoryStream ms = new MemoryStream(file))
            {
                // 创建一个WaveFileReader来读取WAV数据  
                using (WaveFileReader reader = new WaveFileReader(ms))
                {
                    // 创建一个WaveOutEvent来播放音频  
                    using (WaveOutEvent outputDevice = new WaveOutEvent())
                    {
                        // 初始化输出设备并播放  
                        outputDevice.Init(reader);
                        outputDevice.Play();

                        // 等待播放完成，或者根据需要设置其他逻辑（例如，用户输入停止）  
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        outputDevice.Dispose();
                    }
                }
            }
        };
        public void Playacc(byte[] file)
        {
            Thread thread1 = new Thread(() => PlayAcc(file));
            thread1.Start();
        }
        public void PlayAudio(byte[] file)
        {
            Thread thread1 = new Thread(() => playAudio(file));
            thread1.Start();
        }
        private void InputValue(string value)
        {
            if (value != "")
            {
                if (value.ToLower() == "empty")
                {
                    //清空包装材料
                    MaterialSkuList.Text = "[不使用包装材料]";
                    DbScanInputBox.Focus();
                    PlayAudio(AudioMap["materialclear"]);
                }
                else if (MaterialSkuMap.ContainsKey(value))
                {
                    //包装材料
                    MaterialSkuList.Text = MaterialSkuMap[value].GoodsName;
                    DbScanInputBox.Focus();
                    PlayAudio(AudioMap["changeMaterial"]);
                    switch (selectPackagingType.SelectedValue.ToString())
                    {
                        case "3":
                            MaterialSkuList.Text = "[不使用包装材料]";
                            break;
                        case "2":
                            selectPackagingType.Text = "记住上次";
                            break;
                    }

                }
                else
                {
                    //物流单号
                    PostBillNo(value);
                }
            }
        }
        private void showCount()
        {
            count_label.Invoke((Action)(() =>
            {
                count_label.Text = postOrderCount.ToString();
            }));
        }
        private async void TestCommand(string value)
        {
            Dictionary<string, object> postData = new Dictionary<string, object>();
            postData["deliverybulkno"] = value;
            Task<YB.returnmsg> mlisttask = YbWeb.Post(User.GetHostUrl() + "/wmsapi/getinfo/", "deliverybulkdistribution", postData);
            YB.returnmsg response = await mlisttask;
            Console.WriteLine(response.ToString());
        }
        private async void PostBillNo(string value, int weight)
        {
            if (selectWeightType.SelectedValue.ToString() != "3" && weight == 0)
            {
                PlayAudio(AudioMap["weight0"]);
                return;
            }
            if (selectPackagingType.SelectedValue.ToString() == "3" && MaterialSkuList.SelectedValue.ToString() == "0")
            {
                PlayAudio(AudioMap["needmaterial"]);
                return;
            }
            Dictionary<string, object> postData = new Dictionary<string, object>();
            postData["id"] = value;
            postData["packageWeight"] = weight;
            postData["materialGoodsId"] = MaterialSkuList.SelectedValue.ToString();
            OrderCount++;
            SaleOrderInfo saleOrderInfo = new SaleOrderInfo();
            saleOrderInfo.Id = OrderCount.ToString();
            saleOrderInfo.BillNo = value;
            saleOrderInfo.Weight = weight.ToString();
            saleOrderInfo.MaterialName = MaterialSkuList.Text;
            saleOrderInfo.Pkey = saleOrderInfo.Id + value;
            saleOrderInfo.State = "准备中...";
            Console.WriteLine(selectWeightType.SelectedValue.ToString());
            if (selectWeightType.SelectedValue.ToString() == "3")
            {
                saleOrderInfo.Usedgoodsweight = true;
                postData["usedgoodsweight"] = true;
            }
            OrderPostData nowPostData = new OrderPostData();
            nowPostData.Index = saleOrderInfo.Id;
            nowPostData.BillNo = value;
            nowPostData.Pkey = saleOrderInfo.Pkey;
            nowPostData.Data = postData;
            nowPostData.SaleOrder = saleOrderInfo;
            ybListView1.Add(saleOrderInfo);
            ybListView1.ScrollTop();
            await orderChannet.Writer.WriteAsync(nowPostData);
            //包装材料修改
            switch (selectPackagingType.SelectedValue.ToString())
            {
                case "3":
                    MaterialSkuList.Text = "[不使用包装材料]";
                    break;
            }
        }
        private async void PostBillNo(string value)
        {
            int width = 0;
            bool usegoodswidth = false;
            selectWeightType.Invoke((Action)(() =>
            {
                switch (selectWeightType.SelectedValue.ToString())
                {
                    case "1":
                        if (WeightInput.Text == "")
                        {
                            width = 0;
                        }
                        else
                        {
                            width = int.Parse(WeightInput.Text);
                        }
                        break;
                    case "2":
                        if (WeightInput.Text == "")
                        {
                            width = 0;
                        }
                        else
                        {
                            width = int.Parse(WeightInput.Text);
                        }
                        break;
                    case "3":
                        if (WeightInput.Text == "")
                        {
                            width = 0;
                        }
                        else
                        {
                            width = int.Parse(WeightInput.Text);
                        }
                        usegoodswidth = true;
                        break;
                }
                if (!usegoodswidth && width == 0)
                {
                    MessageBox.Show("重量不能为0", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                if (selectPackagingType.SelectedValue.ToString() == "3" && MaterialSkuList.SelectedValue.ToString() == "0")
                {
                    MessageBox.Show("每次必选的情况下，必须选择一个包装材料", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                PostBillNo(value, width);
            }));
        }

        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("退出后聚星打印录像之类的无法使用，确定要退出吗？", "警告", MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Environment.Exit(0);
            }
        }

        private void 刷新打印机列表ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            List<YB.PrintTask.PrintListItem> printList = YB.PrintTask.GetPrintList();
            PrintTab.TabPages.Clear();
            foreach (YB.PrintTask.PrintListItem item in printList)
            {
                ListBox listBox = new ListBox();
                TabPage tab = new TabPage();
                tab.Text = item.Name;
                tab.Name = item.Name;
                tab.Controls.Add(listBox);
                listBox.Dock = DockStyle.Fill;
                PrintTab.TabPages.Add(tab);
            }
        }

        private void 检查更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkUpdate(true);
        }

        private void selectPackagingType_SelectedIndexChanged(object sender, EventArgs e)
        {
            Console.WriteLine(selectPackagingType.SelectedValue.ToString());
            if (selectPackagingType.SelectedValue.ToString() == "2")
            {
                MaterialSkuList.Text = "[不使用包装材料]";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (DbScanInputBox.Text != "")
            {
                InputValue(DbScanInputBox.Text);
            }
        }
        private String GetSocketUrl(string url)
        {
            Uri uri = new Uri(url);
            string webSocketScheme = "ws";
            if (uri.Scheme == "https")
            {
                webSocketScheme = "wss";
            }
            string path = uri.IsAbsoluteUri ? uri.AbsolutePath : uri.PathAndQuery;
            return $"{webSocketScheme}://{uri.Authority}{path}";
        }
        private Uri GetSocketUri(string url)
        {
            Uri uri = new Uri(url);
            string webSocketScheme = "ws";
            if (uri.Scheme == "https")
            {
                webSocketScheme = "wss";
            }
            string path = uri.IsAbsoluteUri ? uri.AbsolutePath : uri.PathAndQuery;
            string webSocketUrl = $"{webSocketScheme}://{uri.Authority}{path}";
            return new Uri(webSocketUrl);
        }
        public string MakeUrl(string host, string url)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentException("Host must not be null or empty.", nameof(host));
            }

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("URL must not be null or empty.", nameof(url));
            }

            // 移除 host 末尾的斜杠（如果有）
            if (host.EndsWith("/"))
            {
                host = host.TrimEnd('/');
            }

            // 移除 url 开头的斜杠（如果有）
            if (url.StartsWith("/"))
            {
                url = url.TrimStart('/');
            }

            // 组合 host 和 url
            return $"{host}/{url}";
        }

        private void DbScanInputBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) // ASCII 编码 13 对应回车键
            {
                String value = DbScanInputBox.Text;
                DbScanInputBox.Text = "";
                Task.Run(() => InputValue(value));
                e.Handled = true;
            }
        }

        private void clear_count_Click(object sender, EventArgs e)
        {
            postOrderCount = 0;
            showCount();
        }

        private void printthisprintercode_Click(object sender, EventArgs e)
        {
            JObject user = YB.User.GetUserInfo();
            if (user == null)
            {
                MessageBox.Show("请先登录才能使用此功能","错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }
            string uid = "";
            YB.Config.ReadJObject(user, "Uid", ref uid);
            if (uid == ""||uid=="0")
            {
                MessageBox.Show("请先登录才能使用此功能", "错误", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }
            string ptemp= "{\"pagedata\":{\"width\":76,\"height\":130,\"customTempTop\":76.7,\"ratio\":3.76562,\"landscape\":\"true\",\"pxwidth\":489.53060000000005,\"pxheight\":286.18712,\"bgenx\":40,\"bgeny\":20},\"nodes\":[{\"type\":\"label\",\"title\":\"横排文本\",\"x\":29,\"y\":0,\"width\":76,\"height\":12,\"text\":\"<%=data.GoodsName%>\",\"color\":\"#000\",\"horizontalalign\":\"center\",\"verticalalign\":\"center\",\"fontsize\":12,\"fontbold\":\"normal\",\"fontfamily\":\"微软雅黑\",\"align\":\"horizontal\",\"icon\":\"fad fa-text-width\",\"opacity\":1,\"caption\":\"标签类-商品名称\"},{\"type\":\"qrcode\",\"codetype\":\"\",\"title\":\"二维码\",\"x\":38,\"y\":13,\"width\":58,\"height\":58,\"isloading\":false,\"text\":\"<%=data.GoodsSn%>\",\"color\":\"#000\",\"reverse\":false,\"wordbreak\":false,\"icon\":\"fad fa-qrcode\",\"caption\":\"标签类-商品编码\",\"image\":{}}],\"var\":\"sn6b7c-1735806895478-07318\"}  ";
            YB.PrintTask.PrintTemplate template = new PrintTask.PrintTemplate();
            template = JsonConvert.DeserializeObject<PrintTask.PrintTemplate>(ptemp); 
            string printername = PrintTab.SelectedTab.Text;
            JObject qr = new JObject();
            qr.Add("CodeType", "SetUsePrinter");
            qr.Add("Id", uid);
            qr.Add("Name", printername);
            string qrjson=qr.ToString();
            JObject data = new JObject();
            data.Add("GoodsName", printername);
            data.Add("GoodsSn", qrjson);
            YB.PrintTask.AddNewPrintTask(YB.PrintTask.GetDefaultPrintName(), "id-" + DateTime.Now.ToString(), template, data);
        }
    }
}
